<template>
    <div class="chat-container">
        <div class="chat-messages" ref="messagesContainer">
            <!-- 消息列表 -->
            <template v-for="item in msgList" :key="item.id">
                <!-- 时间条 -->
                <div v-if="item.showTime" class="time-item">
                    {{ item.stringTime }}
                </div>

                <!-- 消息条 -->
                <div :class="['message', item.sender === currentUserId ? 'mine' : 'others']">
                    <!-- 对方消息 -->
                    <div v-if="item.sender !== currentUserId" class="others-content">
                        <img class="avatar" :src="avatar" alt="avatar">
                        <div class="content-bubble">{{ item.content }}</div>
                    </div>

                    <!-- 自己消息 -->
                    <div v-else class="mine-content">
                        <img v-if="item.deliverStatus === 3" class="error-icon" src="../../../assets//icons/!.svg">
                        <img v-else-if="item.deliverStatus === 1" class="loading-icon"
                            src="../../../assets//icons/loading.svg">
                        <div class="content-bubble">
                            {{ item.content }}
                        </div>
                        <img class="avatar" :src="currentUserAvatar" alt="my-avatar">
                    </div>
                </div>
            </template>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
            <input v-model="inputMsg" @keyup.enter="sendMessage" placeholder="输入消息...">
            <button @click="sendMessage">发送</button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { useRoute } from 'vue-router'
import { getMsgList,cleanUnread } from '@/api/Mmp/message'
import { sendMessage as senderSocketMsg } from '@/services/WebSocketService'
import { useMessageStore } from '@/store/messageStore'

dayjs.extend(relativeTime)

const route = useRoute();
const receiverId = route.query.receiverId; // 或者从路由参数获取
const avatar = route.query.avatar as string;
const currentUserAvatar = ref('https://dragonweb-bucket.oss-cn-beijing.aliyuncs.com/48d72a98-5e58-4b93-b213-e44340ab5dfc.jpg');
const currentUserId = 1;

interface MessageItem {
    id: number;
    sender: number;
    content: string;
    time: number[]; // 后端返回的时间数组
    showTime: boolean; // 是否显示时间条
    stringTime: string; // 格式化后的时间
    date: Date; // 转换后的日期对象
    deliverStatus?: number; // 新增发送状态
    tempId?: string; // 新增临时ID字段
}

const messagesContainer = ref<HTMLElement>();
const msgList = ref<MessageItem[]>([]);
const inputMsg = ref('');

const initMessages = async () => {
    try {
        const result = await getMsgList(receiverId);
        const messages = result.data as MessageItem[];

        // 处理消息列表
        messages.forEach(msg => {
            // 将时间数组转换为Date对象
            const [year, month, day, hour, minute, second] = msg.time;
            msg.date = new Date(year, month - 1, day, hour, minute, second);
        });

        // 计算showTime和stringTime
        let previousDate: Date | null = null;
        messages.forEach((msg, index) => {
            if (index === 0) {
                msg.showTime = true;
            } else {
                const diff = msg.date.getTime() - previousDate!.getTime();
                msg.showTime = diff > 2 * 60 * 1000;
            }

            // 格式化时间
            const now = dayjs();
            const msgTime = dayjs(msg.date);
            if (msgTime.isSame(now, 'day')) {
                msg.stringTime = msgTime.format('HH:mm');
            } else if (msgTime.isSame(now.subtract(1, 'day'), 'day')) {
                msg.stringTime = `昨天 ${msgTime.format('HH:mm')}`;
            } else {
                msg.stringTime = msgTime.format('YYYY/M/D HH:mm');
            }

            previousDate = msg.date;
        });

        msgList.value = messages;
        nextTick(scrollToBottom);
    } catch (error) {
        console.error(error);
    }
};


interface PendingMessage {
    timerId: number;
    tempId: string;
}

// 在原有变量定义后添加
const pendingTimers = ref<Map<string, PendingMessage>>(new Map());

const sendMessage = () => {
    if (!inputMsg.value.trim()) return;
    // 生成唯一临时ID（使用时间戳+随机数）

    const tempMsgId = `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    const newMsg: MessageItem = {
        id: Date.now(),
        sender: currentUserId,
        content: inputMsg.value.trim(),
        time: [
            new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds()
        ],
        showTime: true, // 默认显示时间条
        stringTime: '',
        date: new Date(), // 默认值，后续会覆盖
        deliverStatus: 1, // 初始状态为发送中
        tempId: tempMsgId // 设置临时ID
    };

    // 处理新消息的date、showTime和stringTime
    const timeArray = newMsg.time;
    const newDate = new Date(timeArray[0], timeArray[1] - 1, timeArray[2], timeArray[3], timeArray[4], timeArray[5]
    );
    newMsg.date = newDate;

    // 计算showTime
    if (msgList.value.length > 0) {
        const lastMsg = msgList.value[msgList.value.length - 1];
        const diff = newDate.getTime() - lastMsg.date.getTime();
        newMsg.showTime = diff > 2 * 60 * 1000;
    }

    // 格式化stringTime
    const now = dayjs();
    const msgTime = dayjs(newDate);
    if (msgTime.isSame(now, 'day')) {
        newMsg.stringTime = msgTime.format('HH:mm');
    } else if (msgTime.isSame(now.subtract(1, 'day'), 'day')) {
        newMsg.stringTime = `昨天 ${msgTime.format('HH:mm')}`;
    } else {
        newMsg.stringTime = msgTime.format('YYYY/M/D HH:mm');
    }

    msgList.value.push(newMsg);
    nextTick(scrollToBottom);

    // 启动超时定时器（新增部分）
    const timerId = window.setTimeout(() => {
        const targetMsg = msgList.value.find(msg => msg.tempId === tempMsgId);
        if (targetMsg && targetMsg.deliverStatus === 1) {
            targetMsg.deliverStatus = 3;
            pendingTimers.value.delete(tempMsgId);
        }
    }, 10000); // 10秒超时

    pendingTimers.value.set(tempMsgId, {
        timerId: timerId,
        tempId: tempMsgId
    });



    // 构建消息对象
    const message = {
        toUserId: receiverId,  // 接收方 ID（从路由参数获取）
        content: inputMsg.value.trim(),
        msgId: tempMsgId // 使用临时ID
    };

    try {
        // 通过 WebSocket 发送消息
        senderSocketMsg(message);
    } catch {
        console.log('消息发送失败！')
        newMsg.deliverStatus = 3;
    }

    inputMsg.value = '';
}



//消息滚动至最下方
const scrollToBottom = () => {
    if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
};

// 在setup中添加：
const messageStore = useMessageStore();

const handleWebSocketMessage = (message: any) => {
    if (message.senderId === 'system') {
        // 处理系统消息（发送状态更新）
        const targetMsg = msgList.value.find(msg => msg.tempId === message.msgId);
        if (targetMsg) {
            // 清除定时器（新增部分）
            const pending = pendingTimers.value.get(message.msgId);
            if (pending) {
                window.clearTimeout(pending.timerId);
                pendingTimers.value.delete(message.msgId);
            }

            targetMsg.deliverStatus = message.delieveStatus;
            if (message.delieveStatus === 2) {
                delete targetMsg.tempId;
            }
        }
    } else {
        // 处理普通消息（新增完整处理逻辑）
        const parseMessage = (msg: any): MessageItem => {
            // 转换时间数组为Date对象
            const timeArray = msg.time || [
                new Date().getFullYear(),
                new Date().getMonth() + 1,
                new Date().getDate(),
                new Date().getHours(),
                new Date().getMinutes(),
                new Date().getSeconds()
            ];

            const date = new Date(
                timeArray[0],
                timeArray[1] - 1,
                timeArray[2],
                timeArray[3],
                timeArray[4],
                timeArray[5]
            );

            // 计算显示时间
            let showTime = true;
            if (msgList.value.length > 0) {
                const lastMsg = msgList.value[msgList.value.length - 1];
                const diff = date.getTime() - lastMsg.date.getTime();
                showTime = diff > 2 * 60 * 1000;
            }

            // 格式化时间
            const now = dayjs();
            const msgTime = dayjs(date);
            let stringTime = '';
            if (msgTime.isSame(now, 'day')) {
                stringTime = msgTime.format('HH:mm');
            } else if (msgTime.isSame(now.subtract(1, 'day'), 'day')) {
                stringTime = `昨天 ${msgTime.format('HH:mm')}`;
            } else {
                stringTime = msgTime.format('YYYY/M/D HH:mm');
            }

            return {
                id: msg.id || Date.now(),
                sender: msg.senderId,
                content: msg.content,
                time: timeArray,
                showTime,
                stringTime,
                date,
                deliverStatus: 2 // 接收消息默认为发送成功
            };
        };

        if (Number(message.senderId) === Number(receiverId)) {
            // 当前聊天窗口的消息
            const newMsg = parseMessage(message);
            msgList.value.push(newMsg);
            //清除自己和对象的未读消息
            console.log("清除自己和对象的未读消息")
            cleanUnread(message.senderId).catch((error)=>{
                console.log('清除未读消息失败！',error)
            })
            //减少总未读数
            messageStore.totalUnread--;
            nextTick(scrollToBottom);
        } else {
            // 其他窗口的消息
            messageStore.incrementUnread(message.senderId);
        }
    }
};



onMounted(() => {
    window.$eventBus?.on('message-received', handleWebSocketMessage);
    initMessages();
    nextTick(scrollToBottom);
});

onUnmounted(() => {
    pendingTimers.value.forEach(pending => {
        window.clearTimeout(pending.timerId);
    });
    pendingTimers.value.clear();
    window.$eventBus?.off('message-received', handleWebSocketMessage);
});

</script>

<style scoped>
.chat-container {
    height: 100%;
    background: #f8f8f8;
    display: flex;
    flex-direction: column;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
}

.loading-icon {
    align-self: center;
    width: 20px;
    height: 20px;
    margin: 0 10px;
    animation: rotating 2s linear infinite;
}

.error-icon {
    align-self: center;
    margin: 0 10px;
    width: 20px;
    height: 20px;
    color: #f56c6c;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.message {
    display: flex;
    align-items: flex-end;
    margin: 8px 0;
    max-width: 80%;

}

.mine {
    justify-self: right;
}

.others {
    justify-self: left;
}


.others-content {
    display: flex;
}

.mine-content {
    display: flex;
}

.avatar {
    width: 36px;
    height: 38px;
    /* border-radius: 50%;圆角头像 */
    margin: 0 8px;
}

.content-bubble {
    max-width: calc(100% - 48px);
    padding: 8px 12px;
    border-radius: 16px;
    word-break: break-word;
}

.others .content-bubble {
    background-color: white;
    color: #333;
    margin-right: auto;
}

.mine .content-bubble {
    background-color: #4CD964;
    color: white;
    margin-left: auto;
}

.time-item {
    margin: 12px auto;
    max-width: 200px;
    text-align: center;
    font-size: 12px;
    color: #999;
    background: #f1f1f1;
    padding: 4px 8px;
    border-radius: 16px;
}

.input-area {
    padding: 12px;
    background: white;
    display: flex;
    border-top: 1px solid #e5e5e5;
}

.input-area input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #e5e5e5;
    border-radius: 20px;
    margin-right: 8px;
    outline: none;
}

.input-area button {
    padding: 8px 16px;
    background: #4CD964;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: opacity 0.3s;
}

.input-area button:hover {
    opacity: 0.9;
}

.input-area button:active {
    opacity: 0.8;
}
</style>